<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="navbar-item" @click="showProductModal = true">
        <text class="iconfont icon-add"></text>
        <text style='font-size: 13px;'>新增商品</text>
      </view>
      <view class="navbar-item">
        <text class="iconfont icon-barcode"></text>
        <text style='font-size: 13px;'>扫条形码</text>
      </view>
      <view class="navbar-item">
        <text class="iconfont icon-detail"></text>
        <text style='font-size: 13px;'>切换明细</text>
      </view>
    </view>

    <!-- 搜索和分类选择 -->
    <view class="search-and-category">
      <input type="text" class="search-input" placeholder="输入商品名称以搜索" style="width: 60%;" v-model = "SelectInfo" />
	  <button style="width: 30%;" @click="Select">搜索</button>
    </view>
	
	<!-- 空空如也提示 -->
	<view v-if="products.length === 0" style='display: flex;align-items: center;justify-content: center;margin-top: 50px;'>
	  <image src='../../Resources/Image/空空如也.png' style='width: 120px;height:120px;'></image>
	  <div><span style="font-size: 20px; font-weight: bold; color: #b3b3b3">这里空空如也</span></div>
	</view>
	

    <!-- 商品列表 -->
    <view class="product-list">
      <view v-for="(product, index) in products" :key="index" class="product-card" @click="ToGoods(product.goods_sn)">
        <view class="product-image">
          <image src="../../static/logo.png" mode="aspectFill" class="image-style"></image> 
        </view>
        <view class="product-info">
          <view class="product-name" style='font-size: 17px;font-weight: bold;'>{{ product.goods_name }}</view>
          <view class="product-id" style='font-size: 12px;color:gray'>商品编号：{{ product.goods_sn }}</view>
          <view class="product-stock" style='font-size: 12px;color:seagreen'>商品规格: {{ product.goods_spec }}</view>
          <view class="product-cost" style='font-size: 12px;'>进价: ¥{{ product.goods_price_in }}</view>
          <view class="product-price" style='font-size: 12px;'>售价: ¥{{ product.goods_price_out }}</view>
        </view>
        <view class="product-actions" :style="getBgColor(product.goods_status)">
          {{product.goods_status}}
        </view>
      </view>
    </view>

    <!-- 新增商品弹窗 -->
    <view v-if="showProductModal" class="modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">新增商品</text>
        </view>
        <view class="modal-body">
          <view class="input-label">商品编号</view>
          <input type="text" v-model="newProduct.goods_sn" placeholder="商品编号" class="input-field-rounded" />
          
          <view class="input-label">商品名称</view>
          <input type="text" v-model="newProduct.goods_name" placeholder="商品名称" class="input-field-rounded" />
          
          <view class="input-label">商品规格</view>
          <input type="text" v-model="newProduct.goods_spec" placeholder="商品规格" class="input-field-rounded" />
		  
		  <view class="input-label">商品分类</view>
		  <picker mode="selector" :range="ArrayCategory" @change="onCooperationStatusChange" :value="0">
		    <view class="picker">{{ newProduct.category_name }}</view>
		  </picker>
		  
<!-- 		  <view class="input-label">商品分类</view>
			<select v-model="newProduct.category_name" class="input-field-rounded" @change="onCooperationStatusChange">
			  <option disabled value="">请选择分类</option>
			  <option v-for="category in ArrayCategory" :key="category.value" :value="category.name">
				{{ category.name }}
			  </option>
			</select> -->
          
          <view class="input-label">成本价</view>
          <input type="text" v-model="newProduct.goods_price_in" placeholder="成本价" class="input-field-rounded" />
          
          <view class="input-label">销售价</view>
          <input type="text" v-model="newProduct.goods_price_out" placeholder="销售价" class="input-field-rounded" />
        </view>
        <view class="modal-footer">
          <button @click="submitProduct" class="action-button">提交</button>
          <button @click="showProductModal = false" class="action-button">取消</button>
        </view>
      </view>
    </view>

    <!-- 数据加载提示 -->
    <view class="data-loading" v-if="isLoading">
      数据加载中...
    </view>
  </view>
</template>

<script setup>
import { onMounted, ref,computed } from 'vue';
import { config } from '../../config';
import { TokenStore } from '../../Store/TokenStore';
import { LoginState } from '../../util/LoginSate';
import { onPullDownRefresh , onReachBottom } from "@dcloudio/uni-app"

let products = ref([]);//搜索框展示商品专用

let SelectInfo = ref('');//输入框信息

let AllProducts = ref([]);

const categories = ref([]);
const currentIndex = ref(0);
const isLoading = ref(true);
const showProductModal = ref(false);
const newProduct = ref({
  goods_sn: '',
  goods_name: '',
  goods_spec: '',
  goods_price_in: '',
  goods_stock: '',
  goods_price_out: '',
  category_name:'请选择分类'
  
});

//分页数组
let pageInfo = ref({
	size:5,
	page:1
})

onMounted(() => {
	if(!LoginState()){
		uni.showToast({
		  title: '登录失效',
		  icon: 'error'
		});
		uni.redirectTo({
			url:"/pages/index/index"
		})
		return ;
	}
  AllGoods();
  AllCategory();
});

//----------------------------------下拉刷新/到底加载------------------------------------------

onPullDownRefresh(()=>{
	console.log("下拉刷新")
	pageInfo.value.page = 1;
	AllProducts.value = []
	products.value = []
	AllGoods()
	uni.stopPullDownRefresh()
})

onReachBottom(()=>{
	console.log("到底加载")
	AllGoods()
})

//-----------------------------------------------------------------------------------

//----------------------------------------搜索框方法--------------------------------------------------

function Select(){
	if(SelectInfo.value === ''){
		products.value = AllProducts.value
		return ;
	}
	const searchedGoods = AllProducts.value.filter(item => item.goods_name === SelectInfo.value);
	console.log("查询出数据"+JSON.stringify(searchedGoods))
	products.value = searchedGoods;
}

//--------------------------------------------------------------------------------------------------



//--------------------------------------------分类部分------------------------------------------------

let ArrayCategory = ref([])

//获取所有分类
async function AllCategory(){
	await uni.request({
		url:`${config.baseURL}/Goods/AllCategory`,
		method:'GET',
		header: {
		  'content-type': 'application/json',
		  'Authorization': TokenStore().token,
		},
		success:(res)=>{
			categories.value = JSON.parse(res.data.data);
			console.log("获取分类数据:"+JSON.stringify(categories.value))
			// 清空 ArrayCategory 并填充新的 category_name
			ArrayCategory.value = categories.value.map(item => item.category_name);
			
			console.log("元素赋值成功:"+JSON.stringify(ArrayCategory.value));
		},
		fail:(err)=>{
			uni.showToast({
			  title: err.errMsg,
			  icon: 'error',
			});
			return ;
		}
	})
	
}

//--------------------------------------------------------------------------------------------------------------


function AllGoods() {
  uni.request({
    url: `${config.baseURL}/NGoods/AllGoods`,
    method: 'POST',
	data:pageInfo.value,
    header: {
      'content-type': 'application/json',
      'Authorization': TokenStore().token,
    },
    success: (res) => {
      if (res.data.data === 'error') {
        uni.showToast({
          title: '数据库错误',
          icon: 'error',
        });
      } else {
		  let data = JSON.parse(res.data.data);
		  console.log("收到数据" + JSON.stringify(data));
		  //追加数据
		  products.value.push(...data)
		  AllProducts.value.push(...data)
		  pageInfo.value.page+=pageInfo.value.size//更新分页状态
          
      }
    },
  });
}

//选择分类赋值
const onCooperationStatusChange = (e) => {
  console.log("选择器下标"+e.detail.value)
  console.log("此时数组："+JSON.stringify(ArrayCategory.value))
  newProduct.value.category_name =   ArrayCategory.value[e.detail.value]
  console.log("状态改变"+newProduct.value.category_name);
};

// 新增商品
const addProduct = () => {
  showProductModal.value = true;
  newProduct.value = {
    goods_sn: '',
    goods_name: '',
    goods_spec: '',
    goods_price_in: '',
    goods_stock: '',
    goods_price_out: '',
  };
};

// 提交商品
const submitProduct = () => {
  // 这里应该是调用API来提交商品数据
  // 模拟添加商品到列表
  console.log("新增商品列表"+JSON.stringify(newProduct.value))
  
  if (Object.values(newProduct).some(value => value === '')) {
    uni.showToast({
      title: "请填写所有字段",
      icon: 'error'
    });
  	return ;
  }
  
  uni.request({
  	url:`${config.baseURL}/NGoods/AddGoods`,
	method:'POST',
	data:newProduct.value,
	header: {
	  'content-type': 'application/json',
	  'Authorization': TokenStore().token,
	},
	success:(res)=>{
		if(res.data.data === '令牌过期'){
			uni.showToast({
			  title: "请重新登录",
			  icon: 'error'
			});
		}
		else if(res.data.data === '0'){
			uni.showToast({
			  title: "系统繁忙",
			  icon: 'error'
			});
		}
		else if(res.data.data === '1'){
			uni.showToast({
			  title: "提交成功",
			  icon: 'success'
			});
			showProductModal.value = false;
			AllGoods()
			Object.keys(newProduct.value).forEach(key => {
			  newProduct.value[key] = '';
			});
		}
		else if(res.data.data === 'error'){
			uni.showToast({
			  title: "数据库错误",
			  icon: 'error'
			});
		}
	},
	fail:(err)=>{
		uni.showToast({
		  title: err.errMsg,
		  icon: 'error'
		});
	}
  })
  
};

// 选择分类
const onCategoryChange = (e) => {
  currentIndex.value = e.detail.value;
};

// 跳转到详情页
function ToGoods(good_sn) {
  console.log("收到数据" + good_sn);
  uni.navigateTo({
    url: '/pages/ManageMyGood/ManageMyGood?good_sn=' + encodeURIComponent(good_sn),
  });
}

// 根据商品状态返回不同的背景颜色
const getBgColor = (status) => {
  if (status === '下架') {
    return { backgroundColor: '#f66f66', color: 'white' };
  } else if (status === '上架') {
    return { backgroundColor: '#5aee77', color: 'white' };
  } else {
    return {};
  }
};

// 模拟数据加载
setTimeout(() => {
  isLoading.value = false;
}, 2000);
</script>

<style scoped>
.container {
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  background-color: #f0f2f5;
  color: #2c3e50;
}

.picker {
padding: 10px;
background-color: #eaeaea;
border-radius: 5px;
margin-bottom: 20px;
}

.navbar {
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.navbar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 10px;
  color: #409eff;
  font-size: 15px;
  transition: color 0.3s ease-in-out;
}

.navbar-item:hover {
  color: #66b1ff;
}

.search-and-category {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  margin: 10px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-right: 10px;
  transition: border-color 0.3s ease-in-out;
}

.search-input:focus {
  border-color: #409eff;
}

.category-picker {
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
  cursor: pointer;
  transition: background-color 0.3s ease-in-out;
}

.category-picker:hover {
  background-color: #eaeaea;
}

.product-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 10px;
  width: 100%;
}

.product-card {
  display: flex;
  width: 95%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
overflow: hidden;
transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
height: 135px;
}

.product-card:hover {
transform: translateY(-2px);
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

.product-image {
display: flex;
justify-content: center;
align-items: center;
width: 30%;
height: 100%;
overflow: hidden;
border-radius: 10px;
margin-bottom: 20px;
background-color: #f8f8f8;
}

.image-style {
width: 100px;
height: 120px;
object-fit: cover;
border-radius: 10px;
}

.product-info {
display: flex;
flex-direction: column;
padding: 15px;
flex-grow: 1;
}

.product-name,
.product-id,
.product-stock,
.product-cost,
.product-price,
.product-status {
margin-bottom: 5px;
}

.product-actions {
display: flex;
align-items: center;
justify-content: center;
padding: 10px;
border-radius: 0 8px 8px 0;
cursor: pointer;
transition: background-color 0.3s ease-in-out;
}

.product-actions button {
color: white;
border: none;
background: none;
font-size: 16px;
cursor: pointer;
}

.product-actions button:hover {
color: #ffffff;
}

.data-loading {
text-align: center;
padding: 20px;
font-size: 16px;
color: #888;
}
/* 新增商品弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  width: 90%;
  max-width: 500px; /* 限制弹窗的最大宽度 */
}

.modal-header {
  border-bottom: 1px solid #eaeaea;
  padding-bottom: 10px;
  margin-bottom: 15px;
}

.modal-title {
  font-size: 18px;
  color: #333;
}

.modal-body {
  margin-bottom: 15px;
}

.input-label {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
  display: block; /* 使标签独占一行 */
}

.input-field-rounded {
  width: 95%;
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #eaeaea;
  border-radius: 4px;
  font-size: 14px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
}

.action-button {
  padding: 10px 20px;
  margin-left: 10px;
  border: none;
  border-radius: 4px;
  background-color: #007bff;
  color: white;
  cursor: pointer;
  font-size: 14px;
  width: 55%;
  height: 53px;
}

.action-button2 {
  padding: 10px 20px;
  margin-left: 10px;
  border: none;
  border-radius: 4px;
  background-color: #007bff;
  color: white;
  cursor: pointer;
  font-size: 14px;
  width: 10%;
  height: 53px;
}

.action-button:hover {
  background-color: #0056b3;
}

.action-button:active {
  transform: translateY(2px);
}
</style>